<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container-TmptList">
      <el-input v-model="listQuery.keyrandom" size="small" placeholder="Key" style="width: 200px; " class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.tablename" size="small" placeholder="表名 [模糊查询]" style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.tablenameshow" size="small" placeholder="表名/菜单名[模糊查询]" style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.deleteflag" size="small" placeholder="状态" style="width: 100px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 0px;" size="small" type="primary" icon="el-icon-edit"
                 @click="handleCreateBuildCode">
        源码生成器
      </el-button>
      <el-button class="filter-item" style="margin-left: 0px;" size="small" type="primary" icon="el-icon-edit"
                             @click="handleBankupsAndRestore()">
        备份还原
      </el-button>
      <el-button class="filter-item" style="margin-left: 0px;" size="small" icon="el-icon-setting"
                 @click="pageSettingVisible=true">
        页面设置
      </el-button>

    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      @selection-change="selectionChangeHandle"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      :height="tableHeight"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>

      <el-table-column
        v-for="(col, index) in formThead"
        :key="index"
        :prop="col.name"
        :sortable="col.sort"
        :sort-orders="['ascending', 'descending']"
        :label="col.title"
        :width="col.width"
      >
        <template slot-scope="{row}">
          <span v-if="col.edit">
              <span v-if="col.type === 'select'">
                  <el-select v-if="row.edit"
                             v-model="row[col.name]"
                             class="edit-input" size="mini" >
                    <el-option
                      v-for="item in idTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <span v-else>{{ row[col.name] }}</span>
              </span>
              <span v-else-if="col.type === 'select-multi'">
                  <el-select v-if="row.edit"
                             v-model="row[col.name].id"
                             multiple
                             collapse-tags
                             class="edit-input" size="mini" >
                    <el-option
                      v-for="item in btnTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"/>
                  </el-select>
                  <span v-else>{{ row[col.name].name }}</span>
              </span>
              <span v-else>
                  <el-input v-if="row.edit" v-model="row[col.name]" class="edit-input" size="mini"/>
                  <span v-else>{{ row[col.name] }}</span>
              </span>
          </span>
          <span v-else>{{ row[col.name] }}</span>
        </template>
      </el-table-column>

      <!--操作Button-->
      <el-table-column v-if="!isDropMenu" fixed="right" align="center" min-width="410">
        <template slot="header">
          <el-checkbox v-model="isDropMenu" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
            平铺->下拉
          </el-checkbox>
        </template>
        <template slot-scope="{row}">
          <el-button-group>
            <el-button v-if="!row.edit" type="primary" icon="el-icon-edit" title="编辑" size="mini" style="margin-left: 0px;"
                       @click="row.edit=!row.edit"></el-button>
            <el-button v-show="row.edit" type="success" icon="el-icon-close" title="取消" size="mini"
                       style="margin-left: 0px;" @click="cancelEdit(row)"></el-button>
            <el-button v-if="row.edit" type="success" icon="el-icon-check" title="保存" size="mini"
                       style="margin-left: 0px;" @click="confirmEdit(row)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" title="删除"
                       style="margin-left: 0px;" @click="handleDelete(row)"></el-button>
            <el-button type="primary" size="mini" style="margin-left: 0px;"
                       @click="handleCreateBuildCode4Row(row)">生成源码
            </el-button>
            <el-button type="primary" size="mini" style="margin-left: 0px;" @click="handleShowTmptConfig(row)">模板管理
            </el-button>
            <el-button type="primary" size="mini" style="margin-left: 0px;" @click="handleShowColumnList(row)">列管理
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>

      <el-table-column v-else fixed="right" label="操作" align="center" min-width="160">
        <template slot="header">
          <el-checkbox v-model="isDropMenu" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
            下拉->平铺
          </el-checkbox>
        </template>
        <template slot-scope="{row,$index}">
          <el-button v-show="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="cancelEdit(row)">
            取消
          </el-button>
          <el-button v-if="row.edit" type="success" size="mini" style="margin-left: 0px;" @click="confirmEdit(row)">保存
          </el-button>
          <el-dropdown v-else @command="handleCommand">
            <el-button type="primary" size="mini">
              菜单<i class="el-icon-arrow-down el-icon--right"/>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'coding')">生成源码</el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'config')">模板管理</el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'column')">列管理</el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'update')">编辑</el-dropdown-item>
              <el-dropdown-item :command="beforeHandleCommand($index, row, 'delete')">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

    <!--源码生成器-->
    <el-dialog title="源码生成器" :visible.sync="dialogForm4CodeVisible" :close-on-click-modal="false">
      <build-code/>
      <!--<div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm4CodeVisible = false">
          取消
        </el-button>
      </div>-->
    </el-dialog>

    <!-- 生成源码框 -->
    <el-dialog title="生成源码框" :visible.sync="dialog4GenCodeVisible">
      <GenCode ref="genCode" :keyRandom="tmpt.keyRandom" :tmptId="tmpt.id" :tmptTableName="tmpt.tableName"/>
    </el-dialog>


    <!--tmpt config dialog-->
    <el-dialog :visible.sync="dialog4TmptConfigVisible" :close-on-click-modal="false" title="模板配置管理">
      <TmptConfig ref="tmptConfig" :a1templatetableId="a1templatetableId"/>
    </el-dialog>

    <!--tmpt column dialog-->
    <el-dialog :visible.sync="dialog4ColumnListVisible" :close-on-click-modal="false" title="列管理" width="90%">
      <TmptColumnList ref="tmptColumnList" :a1templatetable-id="a1templatetableId"/>
    </el-dialog>

    <!--BankupsAndRestore-->
    <el-dialog title="备份还原" :visible.sync="dialog4BankupsAndRestoreVisible" width="30%" >
      <TmptBankupRestore ref="tmptBankupRestore" :idListStr="idListStr" :isFromFather="true" @insertFileResult="insertFileResult"/>
    </el-dialog>

    <el-dialog :visible.sync="preview.visible" title="预览" width="90%">
      <tmpt-preview :key-random-prop="preview.keyRandom" :preview-visible="preview.visible"/>
    </el-dialog>

    <el-dialog :visible.sync="pageSettingVisible" title="页面设置">
      <div>
        <h3>列表显示列：</h3>
        <el-checkbox-group v-model="checkboxVal">
          <el-checkbox v-for="(thead,index) in theadOptions" :key="index" :label="thead.name" style="width: 150px;">
            {{thead.title }}
          </el-checkbox>
        </el-checkbox-group>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="savePageSetting">保存</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {
    fetchList,
    updateApi,
    removeApi,
    addTemplatetableColumnApi,
    gen2LevelMenuApi,
    // fetchBankupByIds,
    // insertBankup
  } from './api/tmpt-list-api'
  import waves from '@/directive/waves' // waves directive
  import { parseTime, deleteEmptyProperty, resizeTableHeight } from '@/utils'
  import storageUtil from '@/utils/StorageUtil'
  import Pagination from '@/components/Pagination/index' // secondary package based on el-pagination
  import BuildCode from './build-code'
  import TmptColumnList from './tmpt-column-list'
  import TmptBankupRestore from './tmpt-bankup-restore'
  import TmptConfig from './tmpt-config'
  import GenCode from './gen-code'

  const ColumnShowListCkedKey = 'tmpt-list-column-show-cked-list-key'
  const isDropMenuKey = 'tmpt-list-column-show-isdropmenu-key'

  // 所有列对象
  const theadOptions = [
    { name: 'id', title: 'ID', width: 80, edit: false, sort: 'custom', default: true },
    { name: 'keyrandom', title: 'Key', width: 200, edit: false, sort: false, default: true },
    { name: 'tablename', title: '表名', width: 200, edit: true, sort: false, default: true },
    { name: 'tablenameshow', title: '表名描述', width: 200, edit: true, sort: false, default: true },
    { name: 'version', title: '源码版本', width: 300, edit: true, sort: false, default: true },
    /*{ name: 'one2many', title: 'O2M子表', width: 200, edit: true, sort: false, default: true },*/
    /*{ name: 'tablealiasname', title: '表别名', width: 100, edit: true, sort: false, default: true },*/
    { name: 'idType', title: '主键生成方式', width: 120, edit: true, sort: false, default: true, type:'select' },
    /*{ name: 'foreignkey', title: '外键', width: 100, edit: true, sort: false, default: true },*/
    { name: 'btnMulti', title: '按钮', width: 200, edit: true, sort: false, default: true, type:'select-multi' },
    /*{ name: 'hasaddbtn', title: '添加BTN', width: 200, edit: true, sort: false, default: true },
    { name: 'hasdownloadreportbtn', title: '下载BTN', width: 80, edit: true, sort: false, default: true },
    { name: 'haseditbtn', title: '编辑BTN', width: 80, edit: true, sort: false, default: true },
    { name: 'hasdelbtn', title: '删除BTN', width: 80, edit: true, sort: false, default: true },
    { name: 'hascheckbox', title: '行多选框', width: 80, edit: true, sort: false, default: true },*/
    { name: 'tablenamesql', title: '表sql', width: 300, edit: true, sort: false, default: true },
    { name: 'deleteflag_Str', title: '状态', width: 80, edit: true, sort: false, default: true },
    { name: 'createdate', title: '创建日期', width: 200, edit: false, sort: false, default: true },
    { name: 'modifydate', title: '修改日期', width: 200, edit: false, sort: false, default: true }/*,
    { name: 'createman', title: '创建人', width: 200, edit: false, sort: false, default: true }*/
  ]

  export default {
    name: 'TmptList',
    components: { BuildCode, Pagination, TmptColumnList,TmptBankupRestore, TmptConfig, GenCode },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },

    data() {
      return {
        tableKey: 0,
        // 控制行尾菜单显示模式（下拉->平铺）
        isDropMenu: storageUtil.readBool(isDropMenuKey),
        // 默认表头控制
        theadOptions: theadOptions,
        checkboxVal: [], // checkboxVal
        formThead: [], // 默认表头 Default header

        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          sort: '-id',
          deleteflag: 0
        },
        //备份表的id
        idListStr: '',
        // //上传的file
        // fileList:[],
        // fileListStr:'',
        importanceOptions: [1, 2, 3],
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {},
        dialogFormVisible: false,
        dialogForm4CodeVisible: false,
        dialog4GenCodeVisible: false, // 生成源码框
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        downloadLoading: false,
        dialog4ColumnListVisible: false,
        dialog4BankupsAndRestoreVisible:false,
        dialog4TmptConfigVisible: false,
        a1templatetableId: 0,
        preview_menu_id: 667,
        coding_menu_id: 668,
        preview: {
          keyRandom: 0,
          visible: false
        },
        pageSettingVisible: false,
        tmpt: {
          id: undefined,
          tableName: undefined,
          keyRandom: undefined
        },
        idTypeOptions:[{
            value: 'auto',
            label: 'auto'
        }, {
            value: 'uuid',
            label: 'uuid'
        }, {
            value: 'none',
            label: 'none'
        }],
        btnTypeOptions:[{
          value: 1,
          label: '添加'
        }, {
          value: 2,
          label: '编辑'
        }, {
          value: 3,
          label: '删除'
        }, {
          value: 4,
          label: '报表'
        }, {
          value: 5,
          label: '源码'
        }],
        tableHeight:0, // 表格高度
        filterContainerHeight: 0, // 查询容器高度
        clientHeight: 0 // 浏览器高度
      }
    },

    watch: {
      checkboxVal(valArr) {
        this.formThead = this.theadOptions.filter(i => valArr.indexOf(i.name) >= 0)
        this.tableKey = this.tableKey + 1// 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
      },
      isDropMenu(val) {
        storageUtil.save(isDropMenuKey, val)
      }
    },

    created() {
      this.initLayout()
      this.getList()
    },

    mounted () {
        // 浏览器、元素大小变化时，动态调整table高度
        resizeTableHeight(this, 'filter-container-TmptList')
    },

    beforeCreate() {
      // 读取文件
      FileReader.prototype.reading = function({ encode } = pms) {
        let bytes = new Uint8Array(this.result)    //无符号整型数组
        let text = new TextDecoder(encode || 'UTF-8').decode(bytes)
        return text
      }
      /* 重写readAsBinaryString函数 */
      FileReader.prototype.readAsBinaryString = function(f) {
        if (!this.onload)       //如果this未重写onload函数，则创建一个公共处理方式
        {
          this.onload = e => {  //在this.onload函数中，完成公共处理
            let rs = this.reading()
            console.log(rs)

          }
        }
        this.readAsArrayBuffer(f)  //内部会回调this.onload方法
      }
    },

    methods: {
      initLayout() {
        const defaultCheckedThead = []
        theadOptions.forEach(col => {
          if (col.default) {
            defaultCheckedThead.push(col.name)
          }
        })
        // read localstorage first
        const columnShowListCked = storageUtil.readArr(ColumnShowListCkedKey)
        if (columnShowListCked.length === 0) {
          this.checkboxVal = defaultCheckedThead
        } else {
          this.checkboxVal = columnShowListCked
        }
      },

      getList() {
        //this.listLoading = true
        deleteEmptyProperty(this.listQuery)
        fetchList(this.listQuery).then(result => {
          const items = result.map.rows
          this.total = result.map.total

          // 备份数据，编辑还原用
          this.list = items.map(v => {
            this.$set(v, 'edit', false)
            v.original = Object.assign({}, v)

            return v
          })

          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.listLoading = true
        this.getList()
      },
      handleInsertBackups() {
        insertBankup({ 'fileListStr': this.fileListStr }).then(result => {
          if (result.success) {
            this.getList()
            this.$notify({
              title: '成功',
              message: 'Insert Successfully',
              type: 'success',
              duration: 2000
            })
          }
        })

      },

      // handleBackups() {
      //   fetchBankupByIds({ 'idListStr': this.idListStr }).then(result => {
      //     const items = result.list
      //     this.onClickDownDaily('test.txt', items)
      //   })
      //
      // },
      // onClickDownDaily(name, val) {
      //   let s = JSON.stringify(val)
      //   var export_blob = new Blob([s])
      //   var save_link = document.createElement('a')
      //   save_link.href = window.URL.createObjectURL(export_blob)
      //   save_link.download = name
      //   this.fakeClick(save_link)
      // },
      // fakeClick(obj) {
      //   var ev = document.createEvent('MouseEvents')
      //   ev.initMouseEvent(
      //     'click',
      //     true,
      //     false,
      //     window,
      //     0,
      //     0,
      //     0,
      //     0,
      //     0,
      //     false,
      //     false,
      //     false,
      //     false,
      //     0,
      //     null
      //   )
      //   obj.dispatchEvent(ev)
      // },
      // 多选
      selectionChangeHandle(val) {
        const _this = this
        _this.idListStr = ''
        val.forEach(function(value, key, arr) {
          if (_this.idListStr == '') {
            _this.idListStr += value.id
          } else {
            _this.idListStr += ',' + value.id
          }

          console.log(_this.idListStr)
          // let s = JSON.stringify(value);
          // console.log(s);
          // 结果依次为1，2，3
          // console.log(key)      // 结尾依次为0，1，2
          // console.log(arr)      // 三次结果都为[1,2,3]，该参数貌似没什么用
        })
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {}
      },
      savePageSetting() {
        storageUtil.save(ColumnShowListCkedKey, this.checkboxVal, true)
        this.pageSettingVisible = false
      },

      // 下拉操作菜单
      beforeHandleCommand(index, row, command) {
        return {
          'index': index,
          'row': row,
          'command': command
        }
      },
      handleCommand(command) {
        const row = command.row
        switch (command.command) {
          case 'coding': {
            this.handleCreateBuildCode4Row(row)
            break
          }
          case 'config': {
            this.handleShowTmptConfig(row)
            break
          }
          case 'column': {
            this.handleShowColumnList(row)
            break
          }
          case 'update': {
            row.edit = !row.edit
            break
          }
          case 'delete': {
            this.handleDelete(row)
            break
          }
        }
      },
      // End

      // 源码生成器，在子组件中生成
      handleCreateBuildCode() {
        this.dialogForm4CodeVisible = true
      },
      // 行尾，重新生成源码
      handleCreateBuildCode4Row(row) {
        this.tmpt.id = row.id
        this.tmpt.tableName = row.tablename
        this.tmpt.keyRandom = row.keyrandom
        this.dialog4GenCodeVisible = true
        /*this.$confirm('重新生成的源码，将覆盖原有源码，请备份好，再执行？')
          .then(() => {
            this.addTemplatetableColumn(row)
          })
          .catch(_ => {})*/
      },

      handleDelete(row) {
        this.$confirm('确认删除吗？')
          .then(_ => {
            removeApi({ id: '' + row.id }).then(() => {
              this.getList()
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            })
          })
          .catch(_ => {
          })
      },

      handleShowColumnList(row) {
        this.a1templatetableId = Number(row.id)
        this.dialog4ColumnListVisible = true
        if (this.$refs['tmptColumnList']) {

          let list = this.$refs['tmptColumnList'].getList()
          let s = JSON.stringify(list)
          // console.log('#################')
          // console.log(s)

        }
      },
      handleBankupsAndRestore() {
        this.dialog4BankupsAndRestoreVisible = true
      },
      // show tmpt config dialog
      handleShowTmptConfig(row) {
        this.a1templatetableId = Number(row.id)
        this.dialog4TmptConfigVisible = true
      },
      insertFileResult() {
        this.dialog4BankupsAndRestoreVisible = false
        this.handleFilter()
      },
      cancelEdit(row) {
        // 还原原始值
        Object.keys(row).forEach(key => {
          if (key !== 'original' && key !== 'edit') {
            row[key] = row.original[key]
          }
        })
        row.edit = false
        // row.original.edit = false
        this.$message({
          message: '数据恢复到原始值',
          type: 'warning'
        })
      },
      confirmEdit(row) {
        const param = Object.assign({}, row)
        param.original = {}
        //param.btnMulti = param.btnMulti
        updateApi(param).then((result) => {
          if (result.success) {
            row.edit = false
            // 原始值：更新成最新输入仠
            Object.keys(row).forEach(key => {
              if (key !== 'original' && key !== 'edit') {
                row.original[key] = row[key]
              }
            })
            this.getList() // refresh
            /*this.$notify({
              title: '成功',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })*/
          }
        })
      },

      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>
<style>
</style>
